var times =0;
$(document).ready(function () {
    var duration = Number(5).mul(60);
    times = COOKIE_TOOL.getCookie("onlineTime") ? COOKIE_TOOL.getCookie("onlineTime") : 0;
    setInterval(function () {
        times++;
        COOKIE_TOOL.setCookie("onlineTime", times)
        if(duration == times){
            TOOL.sendOnlineTime()
        }

    }, 1000);
})
var GLOBAL_VAR = {
    cdnUrl: "https://cdn.c20math.com",
    api: function () {
        if (window.location.host.indexOf("192.168")>=0) {
            /*magic的后端地址*/
            if (window.location.host.indexOf("11.10")>-1){
                return 'http://192.168.11.10:8085';
            }/*middle-test的后端地址*/
            else if (window.location.host.indexOf("11.11")>-1){
                return 'http://192.168.11.11:8085';
            }else {
                /*如果是本地开发，默认是middle-test*/
                return 'http://192.168.11.11:8085';
            }
           // return 'http://192.168.10.210:8085';
        } else {
            if (window.location.host.indexOf("c20hf")>=0){
                return 'http://www.c20hf.com:8085';
            }else {
                return 'https://middle.c20math.com/jvapi';
            }
        }
    },
    moocapi: function () {
        if (window.location.host.indexOf("192.168")>=0) {
            return 'http://192.168.11.11/moocapi';
        } else {
            return 'http://120.26.103.125/moocapi';
        }
    },
    pyapi: function () {

        if (window.location.host.indexOf("127.0.0.1")>=0 || window.location.host.indexOf("localhost")>=0) {
            return 'http://' + window.location.host.substring(0, window.location.host.indexOf(":")) + ':5000';
        } else if (window.location.host.indexOf("192.168")>=0 ){
            return 'http://192.168.11.10:8000';
        } else {
            return 'https://middle.c20math.com/pyapi';
        }
    },
    jupyterapi: function () {
        if (window.location.host.indexOf("192.168")>=0) {
            return 'http://192.168.11.13:8001';
        } else {
            return 'http://notebook.c20math.com';
        }
    },
    jupyterToken: "Cz2r.com",
    jupyterLoginUrl: function (userName) {
        return GLOBAL_VAR.jupyterapi() + "/login?token=" + GLOBAL_VAR.jupyterToken +"&user_name=" + userName;
    },
    myTimer: {}
};

/*这里处理2个版本的app, APP接口名称不一致的第一步兼容. */
if (window.MathFunMid) {
    window.MathFun = window.MathFunMid;
}
var COOKIE_TOOL = {

    //存储的临时内容
    setLocalStorage: function (name, value) {
        window.localStorage.setItem(name, value);
    },
    //获取存储的临时内容
    getLocalStorage: function (name) {
        return window.localStorage.getItem(name);
    },
    setCookie: function (name, value, days) {
        // 为了解决400 错误的问题 - 实际存储已经不是cookie了
        this.setLocalStorage(name, value);
        //  如果是存gameInfo,务必把question, remark属性去掉,因为如果question中有svg的话,无法正常存入
        if (name === "gameInfo" || name === "midGameInfo") {
            var valueJson = JSON.parse(value);
            valueJson.question = null;
            valueJson.numArr = null;
            valueJson.allQuestion = null;
            valueJson.remark = null;
            value = JSON.stringify(valueJson);
            this.setLocalStorage(name, value);
        }

        if (name === "userInfo") {
            if(value != ""){
                var valueJson = JSON.parse(value);
                valueJson.classroomList = "";
                value = JSON.stringify(valueJson);
                this.setLocalStorage(name, value);
            }
        }

        //三个参数，一个是cookie的名子，一个是值，最后一个是天数
        var exp = new Date();    //new Date("December 31, 9998");
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + "; path=/; expires=" + exp.toGMTString();
    },
    getCookie: function (name) {
        //先从localStorage里面找. 为了解决400 too large错误的问题
        if(this.getLocalStorage(name) != null){
            return this.getLocalStorage(name);
        }
        //再取cookies函数
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null){
            return unescape(arr[2]);
        }
        return null;
    },
    delCookie: function (name) {
        //删除cookie并重新演示
        // 该函数检查下cookie是否设置，如果设置了则将过期时间调到过去的时间;
        //剩下就交给操作系统适当时间清理cookie啦
        if (COOKIE_TOOL.getCookie(name)) {
            document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    }
};

var TOOL = {
    /**/
    answerId:'',
    studentAnswer:'',
    answerRecordRank:'',
    gameOver: false, // 标记当前游戏是否结束.
    /**
     * 获取最大公约数
     * @param a
     * @param b
     * @returns {*}
     */
    getDivisor: function gcd(a, b) {
        if (a % b === 0) {
            return b;
        }
        return arguments.callee(b, a % b);
    },
    /**
     * 判断两个传入的元素是否有重叠部分
     * @param node1
     * @param node2
     * @returns {boolean}
     */
    isOverlap: function (node1, node2) {
        var rect1 = node1[0].getBoundingClientRect();
        var rect2 = node2[0].getBoundingClientRect();
        return !(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top > rect2.bottom);
    },
    /**
     * 判断两一个坐标点是否在一个dom元素中
     * @param x
     * @param y
     * @param node
     * @returns {boolean}
     */
    isPointInNode: function (x, y, node) {
        for (let i = 0; i <node.length ; i++) {
            let item = node.get(i);
            let rect2 = item.getBoundingClientRect();
            let isIn = (x >  rect2.left &&  x < rect2.right &&  y > rect2.top && y < rect2.bottom);
            if(isIn){
                return true;
            }
        }
        return false;
    },

    jumpToRecordDetail:function () {
        $(".record-answer-detail").click(function () {
            if ($(this).find("button").attr("hasanswer")=="true"){
                JumpToRecordAnswer($(this).find(".record-answer-button")[0]);
            }
        })
    },

    /**
     * 读取查询参数
     * @param variable
     * @returns {string|boolean}
     */
    getQueryVariable: function (variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] === variable) {
                return pair[1];
            }
        }
        return false;
    },

    /**
     * 获取分数html
     * @param num1  整数
     * @param num2  分母
     * @param num3  分子
     * @returns {string}
     */
    getNumContent: function (num1, num2, num3) {
        return '<div class="fractions-root">' +
            '<div style="align-items: center;text-align: center;display: flex;height: 100%;justify-content: center;">' +
            '<div style="display: inline-block;padding-right: 5px;">' + num1 + '</div>' +
            '<div style="display: inline-block;padding-right: 5px;">' +
            '<div style="border-bottom: 1px solid;">' + num3 + '</div>' +
            '<div style="border-top: 1px solid;">' + num2 + '</div>' +
            '</div></div></div>';
    },

    /**
     * 按分割符号直接返回分数的html
     * @param str
     * @param symbol
     */
    getNumContentWithSymbol: function (str, symbol) {
        var result = str;
        if (str.indexOf('#') > 0) {
            var strings = str.split(symbol);
            result = strings.length === 3 ? TOOL.getNumContent(strings[0], strings[1], strings[2]) : TOOL.getNumContent("", strings[0], strings[1]);
        }
        return result;
    },

    /**
     * 计算分数的值
     * @param num1  整数
     * @param num2  分母
     * @param num3  分子
     * @returns {string}
     */
    toCalculateTheFraction: function (num1, num2, num3) {
        num1 = Number(num1);
        num2 = Number(num2);
        num3 = Number(num3);
        return num1 + num3 / num2;
    },

    /**
     * 计算分数（几分之几的分数）
     */
    toCalculateTheFractionWithSymbol: function (fraction, symbol) {
        var result = Number(fraction);
        if (fraction.indexOf('#') > 0) {
            var strings = fraction.split(symbol);
            result = strings.length === 3 ? TOOL.toCalculateTheFraction(strings[0], strings[1], strings[2]) : TOOL.toCalculateTheFraction(0, strings[0], strings[1]);
        }
        return result;
    },

    /**
     * 生成指定范围内得随机整数（如传0，3则在0、1、2、3四个数中随机）
     * @param minNum
     * @param maxNum
     * @returns {number}
     */
    randomNum: function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1);
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum);
            default:
                return 0;
        }
    },

    /**
     * 打乱数组内部顺序
     * @param arr
     * @returns {*}
     */
    shuffle: function (arr) {
        var length = arr.length,
            temp,
            random;
        while (0 !== length) {
            random = Math.floor(Math.random() * length);
            length--;
            // swap
            temp = arr[length];
            arr[length] = arr[random];
            arr[random] = temp;
        }
        return arr;
    },

    /**
     * 返回主页
     */
    goHome: function (versionLevelId) {
        if (window.MathFun) {
            window.MathFun.closeCurrentActivity();
        } else {
            window.location = (window.location.origin + "/index.html?versionLevelId="+versionLevelId);
        }
    },
    /**
     * 判断当前用户是否登录了
     */
    isLogin: function (){
        var alreadyLogin = false;
        if (window.MathFun) {
            if (window.MathFun.getUserInfo()) {
                alreadyLogin = true
            }
        } else {
            var userInfo = TOOL.getUserInfoFromCookie();
            if (userInfo) {
                alreadyLogin = true
            }
        }
        return alreadyLogin;
    },
    /**
     * 展示胜利
     */
    showSuccess: function (completeBtnHandler, hasNext) {
        //发送在线时长统计信息
        TOOL.sendOnlineTime()
        TOOL.gameOver = true;

        var $successModal = $('#successModal');

        var alreadyLogin = false;
        var userInfo = undefined;
        var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('gameInfo'));
        if (window.MathFun) {
            if (window.MathFun.getUserInfo()) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(window.MathFun.getUserInfo());
                TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime, gameInfo.useCount);
                alreadyLogin = true
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
            if (userInfo) {
                TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime, gameInfo.useCount);
                alreadyLogin = true
            }
        }


        if ($successModal.length === 0) {
            var modalHTML = '<div id="successModal" class="result-modal-root">' +
                '    <div class="img-block">' +
                '        <img id="modalImg" src="../img/win.png"/>' +
                '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;height: 3vw; background-color: #b9b9b9; border-radius: 50%;"><img src="../img/btn_close_white.png"></div>' +
                '        <div class="text">你太棒了<br>闯关成功</div>' +
                '        <div class="btn-container">' +
                '            <div class="btn">' + (hasNext ? '下一关' : '返回') + '</div>' +
                '        </div>' +
                '    </div>';
            if (!alreadyLogin) {
                modalHTML += '<div class="name-input">' +
                    '               <div class="btn-container">' +
                    '                   <div class="btn-login">记入排行</div>' +
                    '               </div>' +
                    '             </div>';
            }
            modalHTML += '</div>';
            $('body').append(modalHTML);
        }

        setTimeout(function () {
            var $successModal = $('#successModal');
            TOOL.showSound("../../music/win2.wav");
            $successModal.show();
            $successModal.find('div.btn').click(function () {
                console.info($successModal.find('input[name=name]').val());
                completeBtnHandler($successModal.find('input[name=name]').val());
            });

            $successModal.find('.close-modal').click(function () {
                $successModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '  <div class="btn">' + (hasNext ? '下一关' : '返回') + '</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    completeBtnHandler();
                });

            })

            $successModal.find('#modalImg').click(function () {
                $successModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">' + (hasNext ? '下一关' : '返回') + '</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    completeBtnHandler();
                });

            })

            $successModal.find('div.btn-login').click(function () {
                if (window.MathFun) {
                    if (alreadyLogin) {
                        //获取用户信息后将游戏记录保存
                        TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                    } else {
                        //未登录跳转到Android登录页
                        window.MathFun.jumpLoginActivity();
                    }
                } else {
                    //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
                    if (alreadyLogin) {
                        TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                    } else {
                        TOOL.openLogin()
                    }
                }
            });

        }, 0);
    },

    /**
     * 展示失败
     */
    showFailed: function (failureBtnHandler) {
        //发送在线时长统计信息
        TOOL.sendOnlineTime()
        TOOL.gameOver = true;

        var $failureModal = $('#failureModal');
        var alreadyLogin = false
        var userInfo = undefined;
        var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('gameInfo'));
        if (window.MathFun) {
            var userInfoStr = window.MathFun.getUserInfo()
            if (userInfoStr) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(userInfoStr);
                TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                alreadyLogin = true
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
            if (userInfo) {
                TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                alreadyLogin = true
            }
        }

        if ($failureModal.length === 0) {
            var modalHTML = '<div id="failureModal" class="result-modal-root" style="background: rgba(0, 0, 0, 0.63);">' +
                '    <div class="img-block">' +
                '        <img id="modalImg" src="../img/defeated-2.png"/>' +
                '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;"><img src="../img/btn_close_white.png"></div>' +
                '        <div class="text">回答错误，换个思路<br>继续加油！</div>' +
                '        <div class="btn-container">' +
                '            <div class="btn">再次挑战</div>' +
                '        </div>' +
                '    </div>';
            if (!alreadyLogin) {
                modalHTML += '<div class="name-input">' +
                    '               <div class="btn-container">' +
                    '                   <div class="btn-login">记入排行</div>' +
                    '               </div>' +
                    '             </div>';
            }
            modalHTML += '</div>';
            $('body').append(modalHTML);
        }

        setTimeout(function () {
            var $failureModal = $('#failureModal');
            TOOL.showSound("../../music/defeated.wav");
            $failureModal.show();
            $failureModal.find('div.btn').click(function () {
                console.info($failureModal.find('input[name=name]').val());
                failureBtnHandler($failureModal.find('input[name=name]').val());
            });

            $failureModal.find('.close-modal').click(function () {
                $failureModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">再次挑战</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    failureBtnHandler();
                });
            })

            $failureModal.find('#modalImg').click(function () {
                $failureModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">再次挑战</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    failureBtnHandler();
                });
            })



            $failureModal.find('div.btn-login').click(function () {
                if (window.MathFun) {
                    if (alreadyLogin) {
                        //获取用户信息后将游戏记录保存
                        TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                    } else {
                        //未登录跳转到Android登录页
                        window.MathFun.jumpLoginActivity();
                    }
                } else {
                    //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
                    if (alreadyLogin) {
                        TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                    } else {
                        TOOL.openLogin()
                    }
                }
            });
        }, 0);
    },
    /**
     * 展示胜利
     */
    showMidSuccess: function (completeBtnHandler, hasNext, nextText) {
        //发送在线时长统计信息
        TOOL.sendOnlineTime()
        TOOL.gameOver = true;

        var $successModal = $('#successModal');

        var alreadyLogin = false;
        var userInfo = undefined;
        var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('midGameInfo'));
        if (window.MathFun) {
            if (window.MathFun.getUserInfo()) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(window.MathFun.getUserInfo());
                TOOL.saveMidRecord(userInfo.id, gameInfo);
                alreadyLogin = true
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
            if (userInfo) {
                TOOL.saveMidRecord(userInfo.id, gameInfo);
                alreadyLogin = true
            }
        }
        let  addRecordAnswer= gameInfo.addRecordAnswer ;
        if ($successModal.length === 0) {
            var modalHTML="";

            if (alreadyLogin&&addRecordAnswer){
                    //这个按钮的获取点击效果其他地方是用  div.btn 来唯一定位获取，为了不对其他地方获取产生影响，需要1. 覆盖class样式，2.不能使用 btn样式
                    modalHTML =   '<div id="successModal" class="result-modal-root" style="background: rgba(0, 0, 0, 0.63);">' +
                        '    <div class="img-block">' +
                        '        <img id="modalImg" src="../../img/win.png"/>' +
                        '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;"><img src="../../img/btn_close_white.png"></div>' +
                        '        <div class="text">你太棒了<br>闯关成功</div>' +
                        '        <div class="btn-container">' +
                        '            <div style="color: white;\n' +
                        '    background: #0384cd;\n' +
                        '    /* padding: 0 16px; */\n' +
                        '    border-radius: 1.5vw;\n' +
                        '    cursor: pointer;\n' +
                        '    width: 10%;\n' +
                        '    display: inline-block;\n' +
                        '    height: 2vw;\n' +
                        '    line-height: 2vw;\n' +
                        '    font-size: 1.5vw;"  class="btn">' + (hasNext ? (nextText ? nextText : '下一关') : '返回') + '</div> <div style="color: white;\n' +
                        '    background: #0384cd;\n' +
                        '    /* padding: 0 16px; */\n' +
                        '    border-radius: 1.5vw;\n' +
                        '    cursor: pointer;\n' +
                        '    width: 13%;\n' +
                        '    display: inline-block;\n' +
                        '    height: 2vw;\n' +
                        '    line-height: 2vw;\n' +
                        '    font-size: 1.5vw;" class="btn_learn">查看记录</div>' +
                        '        </div>' +
                        '    </div>';
            }else {
                 modalHTML = '<div id="successModal" class="result-modal-root">' +
                    '    <div class="img-block">' +
                    '        <img id="modalImg" src="../../img/win.png"/>' +
                    '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;height: 3vw; background-color: #b9b9b9; border-radius: 50%;"><img src="../../img/btn_close_white.png"></div>' +
                    '        <div class="text">你太棒了<br>闯关成功</div>' +
                    '        <div class="btn-container">' +
                    '            <div class="btn">' + (hasNext ? (nextText ? nextText : '下一关') : '返回') + '</div>' +
                    '        </div>' +
                    '    </div>';
            }



            if (!alreadyLogin) {
                modalHTML += '<div class="name-input">' +
                    '               <div class="btn-container">' +
                    '                   <div class="btn-login">记入排行</div>' +
                    '               </div>' +
                    '             </div>';
            }
            modalHTML += '</div>';
            $('body').append(modalHTML);
        }

        setTimeout(function () {
            var $successModal = $('#successModal');
            TOOL.showSound("../../music/win2.wav");
            $successModal.show();
            $successModal.find('div.btn').click(function () {
                console.info($successModal.find('input[name=name]').val());
                completeBtnHandler($successModal.find('input[name=name]').val());
            });

            $successModal.find('.close-modal').click(function () {
                $successModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '  <div class="btn retryBtn" style="right: 12%">再玩一次</div>          <div class="btn nextBtn">' + (hasNext ? (nextText ? nextText : '下一关') : '返回') + '</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.retryBtn').click(function () {
                    window.location.reload();
                });
                $("#lucencyModal").find('div.nextBtn').click(function () {
                    completeBtnHandler();
                });
            })

            $successModal.find('#modalImg').click(function () {
                $successModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">' + (hasNext ? (nextText ? nextText : '下一关') : '返回') + '</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    completeBtnHandler();
                });

            })

            $successModal.find('div.btn-login').click(function () {
                if (window.MathFun) {
                    if (window.MathFun.getUserInfo()) {
                        //获取用户信息后将游戏记录保存
                        userInfo = JSON.parse(window.MathFun.getUserInfo());
                        TOOL.saveMidRecord(userInfo.id, gameInfo);
                        $(".name-input").hide();
                        layer.msg("保存成功！", {icon: 1})
                        alreadyLogin = true
                    } else {
                        //未登录跳转到Android登录页
                        window.MathFun.jumpLoginActivity();
                    }
                } else {
                    //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
                    if (alreadyLogin) {
                        TOOL.saveMidRecord(userInfo.id, gameInfo);
                    } else {
                        TOOL.openLogin(null, true)
                    }
                }
            });

            if (addRecordAnswer){
                $successModal.find('div.btn_learn').click(function () {
                    window.open("/middle/showSquare.html?code=" + TOOL.answerId + "&" + "&language=record"  , 'scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes')
                });
            }

        }, 0);
    },

    /**
     * 展示失败
     */
    showMidFailed: function (failureBtnHandler) {
        //发送在线时长统计信息
        TOOL.sendOnlineTime()
        TOOL.gameOver = true;
        var $failureModal = $('#failureModal');
        var alreadyLogin = false
        var userInfo = undefined;
        var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('midGameInfo'));
    /*添加引导*/
        let addBoot = gameInfo.addBoot ;
        if (window.MathFun) {
            var userInfoStr = window.MathFun.getUserInfo()
            if (userInfoStr) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(userInfoStr);
                TOOL.saveMidRecord(userInfo.id, gameInfo);
                alreadyLogin = true
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
            if (userInfo) {
                TOOL.saveMidRecord(userInfo.id, gameInfo);
                alreadyLogin = true
            }
        }

        if ($failureModal.length === 0) {
            var modalHTML = '<div id="failureModal" class="result-modal-root" style="background: rgba(0, 0, 0, 0.63);">' +
                '    <div class="img-block">' +
                '        <img id="modalImg" src="../../img/defeated-2.png"/>' +
                '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;"><img src="../../img/btn_close_white.png"></div>' +
                '        <div class="text">回答错误，换个思路<br>继续加油！</div>' +
                '        <div class="btn-container">' +
                '            <div class="btn">再次挑战</div>' +
                '        </div>' +
                '    </div>';

            if (addBoot){
                //这个按钮的获取点击效果其他地方是用  div.btn 来唯一定位获取，为了不对其他地方获取产生影响，需要1. 覆盖class样式，2.不能使用 btn样式
                modalHTML =   '<div id="failureModal" class="result-modal-root" style="background: rgba(0, 0, 0, 0.63);">' +
                    '    <div class="img-block">' +
                    '        <img id="modalImg" src="../../img/defeated-2.png"/>' +
                    '        <div class="close-modal" style="position: absolute;top: 10%;right: 25%;width: 3vw;"><img src="../../img/btn_close_white.png"></div>' +
                    '        <div class="text">回答错误，换个思路<br>继续加油！</div>' +
                    '        <div class="btn-container">' +
                    '            <div style="color: white;\n' +
                    '    background: #0384cd;\n' +
                    '    /* padding: 0 16px; */\n' +
                    '    border-radius: 1.5vw;\n' +
                    '    cursor: pointer;\n' +
                    '    width: 13%;\n' +
                    '    display: inline-block;\n' +
                    '    height: 2vw;\n' +
                    '    line-height: 2vw;\n' +
                    '    font-size: 1.5vw;"  class="btn">再次挑战</div> <div style="color: white;\n' +
                    '    background: #0384cd;\n' +
                    '    /* padding: 0 16px; */\n' +
                    '    border-radius: 1.5vw;\n' +
                    '    cursor: pointer;\n' +
                    '    width: 13%;\n' +
                    '    display: inline-block;\n' +
                    '    height: 2vw;\n' +
                    '    line-height: 2vw;\n' +
                    '    font-size: 1.5vw;" class="btn_learn">查看引导</div>' +
                    '        </div>' +
                    '    </div>';
            }



            if (!alreadyLogin) {
                modalHTML += '<div class="name-input">' +
                    '               <div class="btn-container">' +
                    '                   <div class="btn-login">记入排行</div>' +
                    '               </div>' +
                    '             </div>';
            }
            modalHTML += '</div>';
            $('body').append(modalHTML);
        }

        setTimeout(function () {
            var $failureModal = $('#failureModal');
            TOOL.showSound("../../music/defeated.wav");
            $failureModal.show();
            $failureModal.find('div.btn').click(function () {
                console.info($failureModal.find('input[name=name]').val());
                failureBtnHandler($failureModal.find('input[name=name]').val());
            });

            if (addBoot){
                $failureModal.find('div.btn_learn').click(function () {
                    $failureModal.hide()
                    LightTOOL.HandlerLight(gameInfo);
                });
            }

            $failureModal.find('.close-modal').click(function () {
                $failureModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">再次挑战</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    failureBtnHandler();
                });
            })

            $failureModal.find('#modalImg').click(function () {
                $failureModal.hide()
                var lucencyModalHTML = '<div id="lucencyModal" class="lucency-modal-root">' +
                    '            <div class="btn">再次挑战</div>' +
                    '</div>'
                $('body').append(lucencyModalHTML);

                $("#lucencyModal").find('div.btn').click(function () {
                    failureBtnHandler();
                });
            })



            $failureModal.find('div.btn-login').click(function () {
                if (window.MathFun) {
                    if (alreadyLogin) {
                        //获取用户信息后将游戏记录保存
                        TOOL.saveMidRecord(userInfo.id, gameInfo);
                    } else {
                        //未登录跳转到Android登录页
                        window.MathFun.jumpLoginActivity();
                    }
                } else {
                    //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
                    if (alreadyLogin) {
                        TOOL.saveMidRecord(userInfo.id, gameInfo);
                    } else {
                        TOOL.openLogin(null, true)
                    }
                }
            });
        }, 0);
    },

    /**
     * opt.elementId    生成的div元素的ID
     * opt.datas: [{name: 名称, mark:成绩}]
     * opt.mineData: {name: 名称, mark: 成绩, rank: 名次, userId: 用户自己的ID}
     * opt.title: 主标题
     * opt.subTitle: 副标题
     * opt.color: 主色调（orange（默认）, blue）
     * @param opt
     */
    showRank: function (opt) {
        var $rankModal = $('#' + opt.elementId);
        opt.color = opt.color || 'orange';
        var userId = null;
        if (opt.mineData && opt.mineData.userId) {
            userId = opt.mineData.userId;
        }

        if(!opt.datas || opt.datas.length == 0){

            if ($rankModal.length>0){
                $rankModal.remove();
            }
            $('body').append('<div id="' + opt.elementId + '" class="result-modal-root" style="background: rgba(0,0,0,.63);z-index: 9999999">' +
                '    <div class="rank-block ' + opt.color + '">' +
                '        <img class="close-rank" src="../../img/btn_close_white.png" draggable="false"/>' +
                '        <div id="titleSubTitle" style="color: white">' +
                '            <div style="font-size: 4vh">排行榜</div>' +
                '            <div style="font-size: 1.5vw;" class="">' +
                ' <div class="subTitle">' + opt.subTitle + '</div>' +
                '        </div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
                '        <div class="rank-list ' + opt.color + '"><div style="min-height: 390px;display: flex;align-items: center;justify-content: center;color: #7d7979;"><div style="height: 30px;line-height: 30px;display: flex;justify-content: center;align-items: center;;"><img src="/img/middle/empty.png" style="height: 100%; margin-right: 10px;">暂无数据</div></div></div>' +
                '    </div>' +
                '</div>');

            setTimeout(function () {
                $rankModal = $('#' + opt.elementId);
                $rankModal.show();
                $rankModal.find('.close-rank').click(function () {
                    $rankModal.hide();
                });
                $rankModal.find('.no-rank .num').html("-");
            })
            return false;
        }

        var itemHtmlStr = '';
        $.each(opt.datas, function (index, item) {
            var rankClassName = '';
            switch (index) {
                case 0:
                    rankClassName = ' rank-1';
                    break;
                case 1:
                    rankClassName = ' rank-2';
                    break;
                case 2:
                    rankClassName = ' rank-3';
                    break;
                default:
                    rankClassName = '';
            }

            if (item.completeStatus === 0) {
                rankClassName = ' no-rank';
            }

            if (userId && item.userId === userId) {
                rankClassName += ' mine';
            }
            var heacIcon = "../../img/tx.png";
            if(item.headIcon){
                heacIcon = item.headIcon;
            }

            itemHtmlStr += '<div class="rank-item' + rankClassName + '">' +
                '                <div class="num">' + (index + 1) + '</div>' +
                '                <div class="user-rank">' +
                '                    <img src="' + heacIcon + '" draggable="false"/>' +
                '                    <div class="user-rank-name" >' + (rankClassName.indexOf('mine') != -1 ? item.name : TOOL.formatRankName(item.name)) + '</div>' +
                '                    <div class="time"><div><div>' + item.mark + '</div>' + ( item.totalTime ? '<div style="font-size: 14px;">'+ TOOL.timeDiffHourMinSec2(item.totalTime, '小时', '分', '秒') +'</div>' : '' )+ '</div></div>' +
                '                </div>' +
                '            </div>';
        });

        if (opt.mineData && opt.mineData.rank && opt.mineData.rank >10) {
            itemHtmlStr += '<div class="rank-item mine" style="margin-top: 4vh">' +
                '                <div class="num">' + opt.mineData.rank + '</div>' +
                '                <div class="user-rank">' +
                '                    <img src="../../img/tx.png" draggable="false"/>' +
                '                    <div class="user-rank-name" >' + opt.mineData.name + '</div>' +
                '                    <div class="time"><div><div>' + opt.mineData.mark + '</div>' + ( opt.mineData.totalTime ? '<div style="font-size: 14px;">'+ TOOL.timeDiffHourMinSec2(opt.mineData.totalTime, '小时', '分', '秒') +'</div>' : '' )+ '</div></div>' +
                '                </div>' +
                '            </div>';
        }

        if(opt.elementId == 'themeRankDiv'){
            itemHtmlStr += '<div style="color: #b3b3b3;font-size: 14px;text-align: right;padding-right: 30px;">通关数相同用时少的排前面</div>';
        }else{
            itemHtmlStr += '<div style="color: #b3b3b3;font-size: 14px;text-align: right;padding-right: 30px;">用时相同通关早的排前面</div>';
        }

        //避免id重复造成的错误
        if ($rankModal.length === 0) {
            $('body').append('<div id="' + opt.elementId + '" class="result-modal-root" style="background: rgba(0,0,0,.63);z-index: 9999999">' +
                '    <div class="rank-block ' + opt.color + '">' +
                '        <img class="close-rank" src="../../img/btn_close_white.png" draggable="false"/>' +
                '        <div id="titleSubTitle" style="color: white">' +
                '            <div style="font-size: 4vh">' + opt.title + '</div>' +
                '            <div style="font-size: 1.5vw;" class="">' +
                ' <div class="subTitle">' + opt.subTitle + '</div>' +
                '        </div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
                '        <div class="rank-list ' + opt.color + '">' + itemHtmlStr +
                '        </div>' +
                '    </div>' +
                '</div>');

        } else {
            $rankModal.find('#titleSubTitle').empty();
            $rankModal.find('#titleSubTitle').append(
                        '<div style="font-size: 4vh">' + opt.title + '</div>' +
            '            <div style="font-size: 1.5vw" class="item-title">' + opt.subTitle + '</div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
            '<div class="rank-list ' + opt.color + '"></div>');
            $rankModal.find('.rank-list').html(itemHtmlStr);
        }

        setTimeout(function () {
            $rankModal = $('#' + opt.elementId);
            $rankModal.show();
            $rankModal.find('.close-rank').click(function () {
                $rankModal.hide();
            });
            $rankModal.find('.no-rank .num').html("-");
        }, 10);
    },



    showRecord:function (opt) {

        opt.elementId ="record-answer"
        var $rankModal = $('#' + opt.elementId);
        opt.color = opt.color || 'blue';
        var userId = null;

        if ($rankModal.length>0){
            $rankModal.remove();
        }
        if(!opt.list || opt.list.length == 0){
            $('body').append('<div id="' + opt.elementId + '" class="result-modal-root" style="background: rgba(0,0,0,.63);z-index: 9999999">' +
                '    <div class="rank-block ' + opt.color + '">' +
                '        <img class="close-rank" src="../../img/btn_close_white.png" draggable="false"/>' +
                '        <div id="titleSubTitle" style="color: white">' +
                '            <div style="font-size: 4vh">闯关记录</div>' +
                '            <div style="font-size: 1.5vw;" class="">' +
                ' <div class="subTitle">（' + opt.chapterName + '）</div>' +
                '        </div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
                '        <div class="rank-list ' + opt.color + '"><div style="min-height: 390px;display: flex;align-items: center;justify-content: center;color: #7d7979;"><div style="height: 30px;line-height: 30px;display: flex;justify-content: center;align-items: center;;"><img src="../img/middle/empty.png" style="height: 100%; margin-right: 10px;">暂无数据</div></div></div>' +
                '    </div>' +
                '</div>');

            setTimeout(function () {
                $rankModal = $('#' + opt.elementId);
                $rankModal.show();
                $rankModal.find('.close-rank').click(function () {
                    $rankModal.hide();
                });
                $rankModal.find('.no-rank .num').html("-");
            })
            return false;
        }
        var itemHtmlStr = '<div style="">';
        var  insertPanel =false;
        $.each(opt.list, function (index, item) {
            var rankClassName = '';
            switch (index) {
                case 0:
                    rankClassName = ' rank-1';
                    break;
                case 1:
                    rankClassName = ' rank-2';
                    break;
                case 2:
                    rankClassName = ' rank-3';
                    break;
                default:
                    rankClassName = '';
            }

            if (item.completeStatus === 0) {
                rankClassName = ' no-rank';
            }

            if (userId && item.userId === userId) {
                rankClassName += ' mine';
            }

            let innnerHtml  ="";
            let detailHtml='';
            let  levelName="";


            let insertTitle =false;

            $.each(item.list, function (index1, item1) {

                if(index1 == 0){
                    innnerHtml +='<div class="dialog-theme-title"> '+item.themeName+'</div>'
                }
                if (index == 0 && index1 == 0){
                    innnerHtml +='<div class="titlePanel"><div style="width: 12%">关卡</div><div style="width: 19%">做题设备</div>' +
                        '<div style="width: 24%">关卡名称</div>' +
                        '<div style="width: 34%;">做题时间</div>' +
                        '<div style="width: 15%">答题耗时</div>' +
                        '<div style="width: 20%">校排名</div>' +
                        '<div style="width: 20%">全网排名</div>' +
                        '<div style="width: 20%">详情</div>' +
                        '</div>'

                }
                item1.osType = item1.osType ? item1.osType : 1;
                item1.osType = item1.osType ? item1.osType : 1;
               /*  let schoolRank = TOOL.answerRecordRank[item1.id]? TOOL.answerRecordRank[item1.id].schoolRank:'';
                 let allRank =TOOL.answerRecordRank[item1.id]? TOOL.answerRecordRank[item1.id].allRank:'';*/
                let schoolRank =""
                if(levelName != item1.activityLevel){
                    levelName=item1.activityLevel;
                    if(index1 != 0 ){
                        detailHtml += '</div></div><div style="display: flex;background: #b5e4ff;align-items: center;width: 98%;margin-left: 16px;margin-bottom: 16px"><div class="dialog-levels">' + levelName + '</div><div style="width: 100%">'
                    }else{
                        detailHtml += '<div style="display: flex;background: #b5e4ff;align-items: center;width: 98%;margin-left: 16px;margin-bottom: 16px"><div class="dialog-levels">' + levelName + '</div><div style="width: 100%">';
                    }
                }
                let allRank =""
                    detailHtml +="<div class='record-answer-detail' recordId="+item1.id +" ><div style='width: 12%;'><img class='os-type' src='/img/theme/osType-"+item1.osType+".png'/></div> <div style='width: 24%'>"+item1.activityName+"</div> <div style='width: 33%;'>"+TOOL.formatDate(new Date(item1.createTime), 'yyyy.MM.dd    hh:mm')  +"</div> <div style='width: 10%'> "+TOOL.timeDiffHourMinSec(item1.costTime, '小时', '分', '秒') +"</div>" +
                        "<div style='width: 20%' class='schoolrank' >"+schoolRank +"</div><div style='width: 13%'  class='allRank'>"+allRank +"</div> " +
                        "<div style='width: 20%'> <button class='record-answer-button' jumpId="+item1.id+"  hasAnswer="+(item1.studentAnswer? true:false)+" onclick='JumpToRecordAnswer(this)' " +
                        " style='display: "+(item1.studentAnswer? "":"none") + "'>详情</button> </div></div>"
            });



            innnerHtml += detailHtml + '</div>';

            itemHtmlStr +='<div style="">'+innnerHtml+'</div>'
        });




        //避免id重复造成的错误
        if ($rankModal.length === 0) {
            $('body').append('<div id="' + opt.elementId + '" class="result-modal-root" style="background: rgba(0,0,0,.63);z-index: 9999999">' +
                '    <div class="rank-block ' + opt.color + '">' +
                '        <img class="close-rank" src="../../img/btn_close_white.png" draggable="false"/>' +
                '        <div id="titleSubTitle" style="color: white">' +
                '            <div style="font-size: 4vh">闯关记录</div>' +
                '            <div style="font-size: 1.5vw;" class="">' +
                ' <div class="subTitle">（' + opt.chapterName + '）</div>' +
                '        </div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
                '        <div class="rank-list ' + opt.color + '">' + itemHtmlStr +
                '        </div>' +
                '    </div>' +
                '</div>');
        } else {
            $rankModal.find('#titleSubTitle').empty();
            $rankModal.find('#titleSubTitle').append(
                '<div style="font-size: 4vh">闯关记录</div>' +
                '            <div style="font-size: 1.5vw" class="item-title">（' + opt.chapterName + '）</div>' +
                '' + (opt.totalNum ? '<div class="rank-tips"><div class="passNum">已有'+ opt.totalNum +'人参与</div><div class="avgTime">平均用时：'+ opt.avgTime +'</div></div>' : '') +
                '<div class="rank-list ' + opt.color + '"></div>');
            $rankModal.find('.rank-list').html(itemHtmlStr);
        }

        setTimeout(function () {
            $rankModal = $('#' + opt.elementId);
            $rankModal.show();
            $rankModal.find('.close-rank').click(function () {
                $rankModal.hide();
            });
            $rankModal.find('.no-rank .num').html("-");


            //如果这个用户点击过快，这个值还没有请求到的话，那么等待3秒钟再加载，


           var Interval =  setInterval(function () {
              if (TOOL.answerRecordRank){
                  for (var key in TOOL.answerRecordRank){
                      $("div[recordid="+key+"]").find(".schoolrank").text(TOOL.answerRecordRank[key].schoolRank)
                      $("div[recordid="+key+"]").find(".allRank").text(TOOL.answerRecordRank[key].allRank)
                  }
                  clearInterval(Interval)
              }
            },100);
        }, 10);
        TOOL.jumpToRecordDetail();
    },




    /**
     * 获取关卡排名
     * @param gameName  游戏名称
     * @param gameProjectId 关卡ID
     * @param levelNum  第几关
     */
    showLevelRank: function (gameName, gradeId, gameProjectId, levelNum) {
        var userInfo = undefined;
        if (window.MathFun) {
            if (window.MathFun.getUserInfo()) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(window.MathFun.getUserInfo());
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
        }

        var optHandler = function (data) {
            var rankData = [];
            $.each(data.list, function (index, item) {
                var mark = "";
                if (item.useCount) {
                    mark += item.useCount + "次（";
                }
                var minutes = Math.floor(item.useTime / 60);
                var seconds = item.useTime % 60;
                mark += minutes > 0 ? minutes + "分" + seconds + "秒" : seconds + "秒";
                if (item.useCount) {
                    mark += "）";
                }
                rankData.push({
                    name: item.userName,
                    headIcon: item.headIcon,
                    mark: mark,
                    userId: item.userId,
                    completeStatus: item.completeStatus
                })
            });

            var mineData = null;
            if (data.mine) {
                var mark = "";
                if (data.mine.useCount) {
                    mark += data.mine.useCount + "次（";
                }
                var minutes = Math.floor(data.mine.useTime / 60);
                var seconds = data.mine.useTime % 60;
                mark = minutes > 0 ? minutes + "分" + seconds + "秒" : seconds + "秒";
                if (data.mine.useCount) {
                    mark += "）";
                }
                mineData = {
                    name: data.mine.userName,
                    headIcon: data.mine.headIcon,
                    mark: mark,
                    rank: data.mine.orderNum,
                    userId: data.mine.userId
                }
            }

            TOOL.showRank({
                elementId: 'projectRankDiv',
                title: '排行榜',
                subTitle: '' + gameName + '',
                datas: rankData,
                mineData: mineData
            })
        };

        if (userInfo && userInfo.classroomId) {
            TOOL.getLevelRankingByClazz(gradeId, gameProjectId, function (data) {
                optHandler(data);
            })
        } else {
            TOOL.getLevelRanking(gradeId, gameProjectId, 10, function (data) {
                optHandler(data);
            });
        }

        $("#blackboard").find("div[name='look']").html("第"+levelNum+"关（查看题目）")
    },

    /**
     * 获取关卡排名
     * @param gameName  游戏名称
     * @param gameProjectId 关卡ID
     * @param levelNum  第几关
     */
    showMidLevelRank: function (activityTitle, activityId, levelNum) {
        var userInfo = undefined;
        if (window.MathFun) {
            if (window.MathFun.getUserInfo()) {
                //获取用户信息后将游戏记录保存
                userInfo = JSON.parse(window.MathFun.getUserInfo());
            }
        } else {
            //获取用户信息，无信息弹出登录，有信息直接保存游戏记录
            userInfo = TOOL.getUserInfoFromCookie();
        }

        var optHandler = function (data) {
            var rankData = [];
            $.each(data.list, function (index, item) {
                var mark = "";
                if (item.useCount) {
                    mark += item.useCount + "次（";
                }
                // 如果有得分, 就显示得分信息
                if (item.score) {
                    mark += item.score + " 分（";
                }
                var minutes = Math.floor(item.costTime / 60);
                var seconds = item.costTime % 60;
                mark += minutes > 0 ? minutes + "分" + seconds + "秒" : seconds + "秒";
                if (item.useCount || item.score) {
                    mark += "）";
                }
                rankData.push({
                    name: item.userName,
                    headIcon: item.headIcon,
                    mark: mark,
                    userId: item.userId,
                    completeStatus: item.completeStatus
                })
            });

            var mineData = null;
            if (data.mine) {
                var mark = "";
                if (data.mine.useCount) {
                    mark += data.mine.useCount + "次（";
                }
                var minutes = Math.floor(data.mine.useTime / 60);
                var seconds = data.mine.useTime % 60;
                mark = minutes > 0 ? minutes + "分" + seconds + "秒" : seconds + "秒";
                if (data.mine.useCount) {
                    mark += "）";
                }
                mineData = {
                    name: data.mine.userName,
                    headIcon: data.mine.headIcon,
                    mark: mark,
                    rank: data.mine.orderNum,
                    userId: data.mine.userId
                }
            }

            var avgTimes = TOOL.timeDiffHourMinSec2(data.totalTime / data.totalNum, "小时","分","秒")

            TOOL.showRank({
                elementId: 'projectRankDiv',
                title: '排行榜',
                subTitle: '' + activityTitle + '',
                datas: rankData,
                mineData: mineData,
                color: 'mid-blue',
                totalNum: data.totalNum,
                avgTime: avgTimes,
            })
        };

        TOOL.getMidLevelRankingByClazz(activityId, function (data) {
            optHandler(data);
        })

        $("#blackboard").find("div[name='look']").html("第"+levelNum+"关（查看题目）")
    },
    /**
     * 获取大章节排名
     * @param gameName  游戏名称
     * @param themeId 主题Id
     */
    showThemeRank: function (gameName, gradeId, themeId) {
        TOOL.getThemeRanking(gradeId, themeId, 10, function (data) {
            var rankData = [];
            data.list.sort(function (a, b) {
                return a.accessCount - b.accessCount;
            });
            $.each(data.list.reverse(), function (index, item) {
                rankData.push({
                    name: item.userName,
                    headIcon: item.headIcon,
                    mark: "已通" + item.accessCount + "关",
                    userId: item.userId
                })
            });

            var mineData = null;
            if (data.mine) {
                mineData = {
                    name: data.mine.userName,
                    headIcon: data.mine.headIcon,
                    mark: "已通" + data.mine.accessCount + "关",
                    rank: data.mine.orderNum,
                    userId: data.mine.userId
                }
            }

            TOOL.showRank({
                elementId: 'themeRankDiv',
                title: '排行榜',
                subTitle: '（' + gameName + '）',
                datas: rankData,
                mineData: mineData,
                color: 'blue'
            })
        })
    },

    /**
     * 获取主题排名
     * @param chapterId 主题ID
     * @param gameName  游戏名称
     */
    showMidThemeRank: function (chapterId, gameName) {
        TOOL.getMidThemeRanking(chapterId, 10, function (data) {
            var rankData = [];
            data.list.sort(function (a, b) {
                return b.orderNum - a.orderNum;
            });
            $.each(data.list.reverse(), function (index, item) {
                rankData.push({
                    name: item.userName,
                    headIcon: item.headIcon,
                    mark: "已通" + item.activityNum + "关",
                    userId: item.userId,
                    totalTime: item.totalTime
                })
            });

            var avgTimes = TOOL.timeDiffHourMinSec2(data.totalTime / data.totalNum, "小时","分","秒")

            var mineData = null;
            if (data.mine) {
                mineData = {
                    name: data.mine.userName,
                    headIcon: data.mine.headIcon,
                    mark: "已通" + data.mine.activityNum + "关",
                    rank: data.mine.orderNum,
                    userId: data.mine.userId,
                    totalTime: data.mine.totalTime
                }
            }

            TOOL.showRank({
                elementId: 'themeRankDiv',
                title: '排行榜',
                subTitle: '（' + gameName + '）',
                datas: rankData,
                mineData: mineData,
                color: 'mid-blue',
                totalNum: data.totalNum,
                avgTime: avgTimes,
            })
        })
    },


    /**
     * 获取答案排名
     */

    getMidAnswerRecordRank:function () {
        let chapterId = TOOL.getQueryVariable('chapterId');
        TOOL.getMidRecordRank(chapterId, function (result) {
            if (result.code==200){
                let values  =result.result
                TOOL.answerRecordRank =values;
            }
        })
    },

    /**
     * 获取主题排名
     * @param chapterId 主题ID
     * @param gameName  游戏名称
     */
    showMidAnswerRecord: function (chapterId) {
        TOOL.getMidAnswerRecord(chapterId,  function (data) {
            TOOL.showRecord(data);
        },function (result) {
            if (!result){
                layer.msg("登录后查看答题记录!")
            }
        })
    },

    /**
     * opt.elementId    生成的div元素的ID
     * opt.datas: [{name: 名称, mark:成绩}]
     * opt.mineData: {name: 名称, mark: 成绩, rank: 名次, userId: 用户自己的ID}
     * opt.title: 主标题
     * opt.subTitle: 副标题
     * opt.color: 主色调（orange（默认）, blue）
     * @param opt
     */
    showVideo: function (opt) {

        var $rankModal = $('#' + opt.elementId);

        opt.color = opt.color || 'orange';

        var itemHtmlStr = '';
        /*itemHtmlStr = '<div class="video-item">' +
            '                <div class="video-info">' +
            '                    <div class="point-name"><span>' + '全等三角形的性质' + '</span></div>' +
            '                    <div class="video-img video-start" videohref="http://video.c20.org.cn/uploadfile/video/1481017422.mp4"><img src="http://video.c20.org.cn/uploadfile/thumb/1481017422.jpg"/></div>' +
            '                    <div class="video-name">' + '全等三角形的判定' + '</div>' +
            '                </div>' +
            '            </div>';
            */
        $.each(opt.datas, function (index, item) {
            itemHtmlStr += '<div class="video-item">' +
                '                <div class="video-info">' +
                '                    <div class="point-name"><div title="' + (item.pointName ? item.pointName : '视频') +'">' + (item.pointName ? item.pointName : '视频') + '</div></div>' +
                '                    <div class="video-img video-start" videohref="' + item.url + '" pointId="' + item.pointId + '" pointName="' + item.pointName + '" themeName="' + opt.themeName + '" videoName="' + item.name + '" projectId="' + opt.gameProjectId + '" themeId="' + opt.themeId + '" gradeId="' + opt.gradeId + '"><img src="' + (item.img ? item.img : 'img/video-default.png') + '"/></div>' +
                '                    <div class="video-name" title="'+ (item.name ? item.name : '视频') + '">' + (item.name ? item.name : '视频') + '</div>' +
                '                </div>' +
                '            </div>';
        });

        if ($rankModal.length === 0) {
            $('body').append('<div id="' + opt.elementId + '" class="result-modal-root" style="background: rgba(0,0,0,.63);z-index: 9999999">' +
                '    <div class="rank-block ' + opt.color + '">' +
                '        <img class="close-rank" src="../../img/btn_close_white.png" draggable="false"/>' +
                '        <div style="color: white">' +
                '            <div style="font-size: 3vw">' + opt.title + '</div>' +
                '            <div style="font-size: 1.5vw">' + opt.subTitle + '</div>' +
                '        </div>' +
                '        <div class="rank-list ' + opt.color + '">' + itemHtmlStr +
                '        </div>' +
                '    </div>' +
                '</div>');
        } else {
            $rankModal.find('.rank-list').empty();
            $rankModal.find('.rank-list').append(itemHtmlStr);
        }

        if(!$("#videoModal") || $("#videoModal").length == 0){
            var videoModalHtml = '<div id="videoModal" class="result-modal-root" style="display: none">' +
                '    <div class="close-modal" style="position: absolute;top: 5%;right: 10%;width: 3vw;"><img src="../../img/btn_close_white.png"></div>' +
                '    <div class="modal-content">' +
                '        <div class="video-js my-video">' +
                '            <video id="my-video" preload="auto" poster=""></video>' +
                '        </div>' +
                '    </div>' +
                '</div>';
            $("body").append(videoModalHtml);
        }

        setTimeout(function () {
            $rankModal = $('#' + opt.elementId);
            $rankModal.show();
            $rankModal.find('.close-rank').click(function () {
                $rankModal.hide();
                opt.callback();
            });
            $rankModal.find('.no-rank .num').html("-");

            /* 初始化 videojs 播放器 */
            var options = {
                //poster: videoImg,//不自动播放的话，就默认显示图片
                controls: true,//不显示动作条
                autoplay: true,//是否自动播放
                width: 868,
                height: 524,
                controlBar: {
                    muteToggle: false,
                    fullScreen: true
                },
                playbackRates: [0.5, 1, 1.25, 1.5, 1.75, 2]//倍速
            };

            /** 开始播放视频 - 弹窗*/
            $(".video-start").click(function() {
                var videoUrl = $(this).attr("videohref");
                var videoName = $(this).attr("videoName");
                var pointId = $(this).attr("pointId");
                var projectId = $(this).attr("projectId");
                var themeId = $(this).attr("themeId");
                var gradeId = $(this).attr("gradeId");
                var themeName = $(this).attr("themeName");
                var pointName = $(this).attr("pointName");

                var startVideo = function () {
                    videojs("my-video", options, function() {
                        window.myPlayer = this;
                        $("#videoModal .video-con #my-video source").attr("src", videoUrl);
                        myPlayer.src(videoUrl);
                        myPlayer.load(videoUrl);
                        myPlayer.play();

                        AjaxUtil.getUserInfo(function (userInfo) {
                            if (userInfo) {
                                TOOL.startDurationStatistic("PointVideo", videojs('my-video'), userInfo.userId, videoUrl, videoName, pointId, projectId, themeId, gradeId, themeName, pointName)
                            }
                        })
                    });

                    $('#videoModal').show()

                    var soundStatus = TOOL.getSoundStatus();
                    if(soundStatus){
                        window.stopBackgroundMusic();
                    }
                }

                AjaxUtil.getUserInfo(function (userInfo) {
                    if (userInfo) {
                        startVideo()
                    }else{
                        TOOL.openLogin(startVideo)
                    }
                })

                //发送在线时长统计信息
                TOOL.sendOnlineTime()
            });

            // 模态窗消失时，关闭视频
            $('#videoModal').find(".close-modal").on('click', function() {
                $('#videoModal').hide()
                console.log(myPlayer.currentTime())
                myPlayer.pause();
                window.clearInterval(GLOBAL_VAR.myTimer);
                var soundStatus = TOOL.getSoundStatus();
                if(soundStatus){
                    window.playBackgroundMusic();
                }

                //发送在线时长统计信息
                TOOL.sendOnlineTime()
            });
        }, 10);
    },
    /**
     * 获取视频
     * @param gameName  游戏名称
     * @param gameProjectId 关卡ID
     */
    showVideoDialog: function (gameName, gameProjectId, themeId, gradeId, callback) {
        var optHandler = function (data) {
            TOOL.showVideo({
                elementId: 'videoDialogDiv',
                gameProjectId: gameProjectId,
                gradeId: gradeId,
                themeId: themeId,
                themeName: gameName,
                title: '视频学习',
                subTitle: '',
                datas: data,
                callback: callback
            })
        };

        TOOL.getLevelVideo(gameProjectId, function (data) {
            if(data.code == 200){
                optHandler(data.result);
            }else{
                callback()
                layer.msg("获取关卡视频失败！", {icon: 5})
            }
        });
    },
    /**
     * 回到关卡选择页
     * @param themeType
     */
    go2Levels: function (themeType,versionLevelId,themeId,gradeId) {
        themeType = themeType || TOOL.getQueryVariable("themeType");
        versionLevelId = versionLevelId || (TOOL.getQueryVariable("vlId") ? TOOL.getQueryVariable("vlId") : 1);
        gradeId = gradeId || (TOOL.getQueryVariable("gradeId") ? TOOL.getQueryVariable("gradeId") : 1);
        themeId = themeId || (TOOL.getQueryVariable("themeId") ? TOOL.getQueryVariable("themeId") : 0);
        if (window.MathFun) {
            window.MathFun.closeCurrentActivity();
        }else if (window.MagicPuzzle) {
            window.MagicPuzzle.closeWebActivity();
        } else {
            window.location = window.location.origin + "/levels.html?themeType=" + themeType+ "&versionLevelId=" + versionLevelId+ "&gradeId=" + gradeId+ "&themeId=" + themeId;
        }
    },
    /**
     * 回到关卡选择页
     * @param themeType
     */
    go2MiddleLevels: function (chapterId) {
        /**
         * 检测是否是在安卓app下
         */
        if (window.MathFunMid) {
            window.MathFunMid.closeCurrentActivity();
        }else if (window.MagicPuzzle) {
            window.MagicPuzzle.closeWebActivity();
        }  else {
            chapterId = chapterId || TOOL.getQueryVariable("chapterId");
            window.location = window.location.origin + "/middle/theme.html?chapterId=" + chapterId;
        }
    },

    go2NextWork: function (activityId, sectionId) {
        var method = TOOL.getQueryVariable("method") ? TOOL.getQueryVariable("method") : ""
        var gameUrl = window.location.origin + window.location.pathname + "?from=magic&activityId=" + activityId + "&sectionId=" + sectionId + "&method=" + method;
        location.href = gameUrl;
    },

    go2NextLevel: function (params) {
        var qs = window.location.search.substr(1), // 获取url中"?"符后的字串
            items = qs.length ? qs.split("&") : [], // 取得每一个参数项,2
            item = null,
            len = items.length;

        var paramsStr = "";
        for(var i = 0; i < len; i++) {
            item = items[i].split("=");
            var name = decodeURIComponent(item[0]),
                value = decodeURIComponent(item[1]);
            if(name) {
                if(params && params[name]){
                    if(paramsStr == ""){
                        paramsStr += "?"+ name + "=" + params[name];
                    }else{
                        paramsStr += "&"+ name + "=" + params[name];
                    }
                }else{
                    if(name == 'c'){
                        if(paramsStr == ""){
                            paramsStr += "?"+ name + "=" + (parseInt(value) + 1);
                        }else{
                            paramsStr += "&"+ name + "=" + (parseInt(value) + 1);
                        }
                    }else{
                        if(paramsStr == ""){
                            paramsStr += "?"+ name + "=" + value;
                        }else{
                            paramsStr += "&"+ name + "=" + value;
                        }
                    }
                }
            }
        }

        window.location = window.location.origin +  window.location.pathname + paramsStr;
    },

    go2NextLevelWithProject: function (project) {
        var htmlName = project.gameUrl;
        var gameUrl = "";
        var themeId = TOOL.getQueryVariable("themeId") ? TOOL.getQueryVariable("themeId") : 0;
        var themeType = TOOL.getQueryVariable("themeType") ? TOOL.getQueryVariable("themeType") : project.gameThemeType;
        if(htmlName.indexOf("?") != -1){
            gameUrl = window.location.origin + "/" + htmlName + "&gameProjectId=" + project.id + "&gradeId=" + project.gradeId+ "&vlId=" + project.versionLevelId+ "&themeId=" + themeId + "&themeType=" + themeType;
        }else{
            gameUrl = window.location.origin + "/" + htmlName + "?gameProjectId=" +  project.id + "&gradeId=" + project.gradeId+ "&vlId=" + project.versionLevelId+ "&themeId=" + themeId + "&themeType=" + themeType;
        }
        window.location.href = gameUrl;
    },

    go2MidNextLevel: function (gameInfo) {
        var gameUrl = window.location.origin + gameInfo.nextActivity.activityUrl + "?activityId=" + gameInfo.nextActivity.activityId + "&chapterId=" + gameInfo.nextActivity.chapterId ;
        location.href = gameUrl;
    },


    /**
     * 添加背景音乐的元素
     * @param audioSrc
     */
    initVideoCtl: function (blackboard, gameInfo) {
        var defaultDomId = "videoCtr"
        $("#" + defaultDomId).click(function () {
            blackboard.close();
            blackboard.suspendedTimer();
            TOOL.showVideoDialog(gameInfo.activityTitle, gameInfo.id, gameInfo.themeId, gameInfo.gradeId, function () {
                blackboard.startTimer();
            })
        })
    },


    /**
     * 添加背景音乐的元素
     * @param audioSrc
     */
    initSoundCtl: function (audioSrc) {
        var soundStatus = TOOL.getSoundStatus();
        var audioJQ = $("<audio src='" + audioSrc + "' loop id='backgroundMusic'/>");
        audioJQ.appendTo("body");

        var $audioSrc = $('#soundCtr');
        if (soundStatus) {
            $audioSrc.attr('src', '../../img/music-on.png');
            $audioSrc.addClass('playing');
            TOOL.playBackgroundMusic();
        } else {
            $audioSrc.attr('src', '../../img/no_music.png');
            $audioSrc.removeClass('playing');
        }
    },

    /**
     * 读取themeData.json的配置信息来初始化背景音乐
     * @param themeType
     */
    initSoundCtlByThemeType: function(themeType, versionLevelId) {
        themeType = themeType || TOOL.getQueryVariable("themeType");
        TOOL.getThemeInfo(themeType, versionLevelId, function (data) {
            TOOL.initSoundCtl(data.backMusic);
        });
    },

    /**
     * 播放背景音乐
     */
    playBackgroundMusic: function () {
        var elementById = document.getElementById('backgroundMusic');
        if (elementById) {
            elementById.load();
            var promise = elementById.play();
            if (promise !== undefined) {
                promise.then(function () {
                    TOOL.setSoundStatus(true);
                }).catch(function (reason) {
                    console.info(reason);
                    setTimeout(function () {
                        try{
                            elementById.play();
                        }catch (e) {
                            console.log(e);
                        }
                    }, 500);
                });
            }
        }else{
            TOOL.setSoundStatus(true);
        }
    },

    /**
     * 暂停背景音乐
     */
    stopBackgroundMusic: function () {
        var elementById = document.getElementById('backgroundMusic');
        if (elementById) {
            elementById.load();
            elementById.pause();
            TOOL.setSoundStatus(false);
        }else{
            TOOL.setSoundStatus(false);
        }
    },

    /**
     * 产生音效
     * @param audioSrc
     */
    showSound: function (audioSrc) {
        if (TOOL.getSoundStatus()) {
            /**因为音效元素是追加的，所以每次生成之前，将原来的删除掉*/
            $("#hint").remove();
            /**创建audio标签的Jquery对象，然后追加到body进行播放即可*/
            var audioJQ = $("<audio src='" + audioSrc + "' autoplay id='hint'/>");
            audioJQ.appendTo("body");
        }
    },

    /**
     * 获取当前音乐的开放状态
     */
    getSoundStatus: function () {
        if (window.webview) {
            return window.webview.getMusicEnable() ? window.webview.getMusicEnable() : true;
        } else {
            return COOKIE_TOOL.getCookie("soundStatus") ? COOKIE_TOOL.getCookie("soundStatus") === 'true' : true;
        }
    },

    /**
     * 记录音乐状态
     * @param status
     * @returns {boolean|*}
     */
    setSoundStatus: function (status) {
        if (window.webview) {
            return window.webview.saveMusicEnable(status);
        } else {
            return COOKIE_TOOL.setCookie("soundStatus", status, 7);
        }
    },

    /**
     * 保存用户闯关记录
     * @param userName
     * @param gameProjectId
     * @param gradeId
     * @param completeStatus
     * @param useTime
     */
    saveData: function (userId, gameProjectId, gradeId, completeStatus, useTime, useCount) {
        var param = {
            userId: userId,
            gameProjectId: gameProjectId,
            gradeId: gradeId,
            completeStatus: completeStatus,
            useTime: useTime,
            useCount: useCount || undefined
        };
        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/record/create', param, function(result){
            console.log(result);
            if (result.code == 200) {
                // do SomeThing
            }
        });
    },

    /**
     * 保存用户闯关记录，中学版
     * @param userId
     * @param activityId
     * @param costTime
     * @param isFinish
     */
    saveMidRecord: function (userId, gameInfo) {
        /**/
         let sectionId =TOOL.getQueryVariable("sectionId");
        var param = {
            userId: userId,
            activityId: gameInfo.activityId,
            costTime: gameInfo.costTime,
            studentAnswer: gameInfo.studentAnswer,
            isFinish: gameInfo.isFinish,
            recordType: gameInfo.recordType,
            sectionId:sectionId,
        };
        if(gameInfo.score){
            param["score"] = gameInfo.score;
        }
        // 获取平台类型 1 (PC)浏览器端  2 安卓端
        param["osType"] = 1;
        if(window.MathFun){
            param["osType"] = 2;
        }
        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/mid/activity/record/create', param, function(result){
            console.log(result);
            if (result) {
                // do SomeThing
                TOOL.answerId=result.id,
                    TOOL.studentAnswer=result.studentAnswer
            }
        });
    },

    /**
     * 获取关卡排名信息
     * @param gameProjectId  关卡ID
     * @param pageSize  默认10
     * @param handler 结果回调处理
     */
    getLevelRanking: function (gradeId, gameProjectId, pageSize, handler) {
        var param = {
            pageSize: pageSize || 10,
            gradeId: gradeId,
            gameProjectId: gameProjectId
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/record/ranking/level', param, function (result) {
            handler(result);
        });
    },

    /**
     * 获取关卡排名信息(班级排名)
     * @param gameProjectId  关卡ID
     * @param handler 结果回调处理
     */
    getLevelRankingByClazz: function (gradeId, gameProjectId, handler) {
        var param = {
            gradeId: gradeId,
            gameProjectId: gameProjectId
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/record/ranking/level/clazz', param, function (result) {
            handler(result);
        });
    },


    /**
     * 获取关卡排名信息(班级排名)
     * @param gameProjectId  关卡ID
     * @param handler 结果回调处理
     */
    getMidLevelRankingByClazz: function (activityId, handler) {
        var param = {
            activityId: activityId,
            limit: 10
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/mid/activity/record/rank/time', param, function (result) {
            handler(result);
        });
    },
    /**
     * 获取关卡的游戏数据 JSON 列表
     * @param id    gameThemeId
     * @param pageSize  默认10
     */
    getLevelsByThemeId: function (id, pageSize, handler) {
        var param = {
            pageSize: pageSize || 10,
            gameThemeId: id
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/project/game/list', param, function (result) {
            handler(result);
        });
    },

    /**
     * 获取主题排名信息
     * @param themeId  主题ID
     * @param pageSize  默认10
     * @param handler   回调处理结果
     */
    getThemeRanking: function (gradeId, themeId, pageSize, handler) {
        var param = {
            pageSize: pageSize || 10,
            gradeId: gradeId,
            gameThemeId: themeId
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/record/ranking/theme', param, function (result) {
            handler(result);
        });
    },

    /**
     * 获取主题排名信息
     * @param gameThemeId  主题ID
     * @param pageSize  默认10
     * @param handler   回调处理结果
     */
    getMidThemeRanking: function (chapterId, limit, handler) {
        var param = {
            limit: limit || 10,
            chapterId: chapterId
        };

        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/mid/activity/record/rank/num', param, function (result) {
            handler(result);
        });
    },


    /**
     * 查询答题记录列表
     * @param gameThemeId  主题ID
     * @param pageSize  默认10
     * @param handler   回调处理结果
     */
    getMidAnswerRecord: function (chapterId, handler,wrongHandler) {
        var param = {
            chapterId: chapterId
        }
        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/mid/activity/record/my/list', param, function (result) {
            handler(result);
        },function (result) {
                wrongHandler(result);
        })
    },

    /**
     * 获取排名
     * @param chapterId
     * @param handler
     * @param wrongHandler
     */
    getMidRecordRank: function (chapterId, handler) {
        AjaxUtil.getAsync(GLOBAL_VAR.api() + '/mid/activity/record/activityRanking?chapterId='+chapterId ,null, function (result) {
           handler(result)
        });
    },

    /**
     * 获取排名
     * @param chapterId
     * @param handler
     * @param wrongHandler
     */
    getMidRecordRankById: function (recordId, handler) {
        AjaxUtil.getAsync(GLOBAL_VAR.api() + '/mid/activity/record/activityRankingById?recordId='+recordId ,null, function (result) {
            handler(result)
        });
    },


    /**
     * 切换音乐的播放状态和图标
     * @param imgElemId img元素的ID（默认：soundCtr）
     * @param pauseImgSrc   暂停图片的路径（默认：img/no_music.png）
     * @param playImgSrc    播放图片的路径（默认：img/music-on.png）
     */
    changeSoundsIcon: function (imgElemId, pauseImgSrc, playImgSrc) {
        imgElemId = imgElemId ? imgElemId : 'soundCtr';
        pauseImgSrc = pauseImgSrc ? pauseImgSrc : '../../img/no_music.png';
        playImgSrc = playImgSrc ? playImgSrc : '../../img/music-on.png';
        var $audioSrc = $('#' + imgElemId);
        if ($audioSrc.hasClass('playing')) {
            $audioSrc.attr('src', pauseImgSrc);
            $audioSrc.removeClass('playing');
            TOOL.stopBackgroundMusic();
        } else {
            $audioSrc.attr('src', playImgSrc);
            $audioSrc.addClass('playing');
            TOOL.playBackgroundMusic();
        }
    },

    /**
     * 读取themData.json指定themeType的信息
     * @param themeType
     */
    getThemeInfo: function (themeType, versionLevelId, callback) {
        /*$.getJSON('conf/themeData.json', function (data) {
            var data = data.filter(function (item) {
                return item.themeType === themeType;
            })[0];
            callback(data);
        })*/

        var gradeId = TOOL.getQueryVariable("gradeId") ? TOOL.getQueryVariable("gradeId") : 1;
        var params = {"gradeId": gradeId};
        AjaxUtil.postWithJson(GLOBAL_VAR.api()+'/theme/list', params, function(result){
           if(result){
                var data = result.filter(function (item) {
                    return item.themeType === themeType;
                })[0];
                callback(data);
            }
        });
    },
    /**
     * 打开登录页
     */
    openLogin: function (callback, isMid) {
        var HTML = '<div id="login">' +
            '        <div id="login_main">' +
            '            <div id="login_main_top">' +
            '               <div class="top-title"><h2>用户登录</h2></div>' +
            '            </div><!-- main头部结尾-->' +
            '            <hr>' +
            '            <div id="login_main_center" @keyup.enter="login(\'loginForm\')">' +
            '                <form id="loginForm" class="login-container">' +
            '                    <!-- 输入框 -->' +
            '                    <div class="lgD">' +
            '                        <div class="label"><div class="title"><i class="layui-icon layui-icon-username"></i></div></div><input id="account" type="text"' +
            '                               placeholder="输入手机号/账号" class="user-login-input" />' +
            '                    </div>' +
            '                    <div class="lgD">' +
            '                        <div class="label"><div class="title"><i class="layui-icon layui-icon-password"></i></div></div><input id="password" type="password"' +
            '                               placeholder="输入用户密码" class="user-login-input" />' +
            '                    </div>'+
            '                </form>' +
            '            </div><!-- main中部结尾-->' +
            '        </div><!-- main结尾-->' +
            '    </div>';

        TOOL.commonDialog({bgColor: 'login-bg', closeBtn: true, html: HTML, showConfirmButton: true, confirmButtonName: '登录', showCancelButton: false, size: 'min', action: 'login', callback: callback, isMid: isMid}, function () {
        })
    },
    commonDialog: function (option, callback) {
        var $commonDialog = $("#common-dialog");
        var html = "<div id='common-dialog' class='common-dialog-root'><div class='common-dialog "  + (option.size ? option.size : "") + " " + (option.bgColor ? option.bgColor : "") + "'>";

        if(option.closeBtn){
            html += "         <div class='common-dialog-close'><img src='../../img/btn_close_white.png' draggable='false'></div>";
        }

        html += "         <div class='common-dialog-content'>" + option.html;

        var footerHtml = "   <div class='common-dialog-footer'>"
        if(option.showConfirmButton || option.showCancelButton) {
            if (option.showConfirmButton) {
                footerHtml += '<div class="footer-btn confirm-btn">' +
                    '       <button class="layui-btn" lay-submit lay-filter="formDemo">' + option.confirmButtonName + '</button>' +
                    '   </div>';
            }

            if (option.showCancelButton) {
                footerHtml += '<div class="footer-btn cancel-btn">' +
                    '        <button type="reset" class="layui-btn layui-btn-primary">取消</button>' +
                    '   </div>';
            }
        }

        var forgetPasswordHtml = "";
        if(option.action === 'login'){
            forgetPasswordHtml += "<div style='text-align: right; width: 85%; padding: 20px;'><span class='register' style='margin-right: 10px; cursor: pointer;'>注册</span><span class='forgetPwd'>忘记密码？</span></div>"
        }

        html += footerHtml + forgetPasswordHtml + "         </div>";

        html += "   </div>";
        html += "</div>" +
            "<div class='model-bg'></div>" +
            "</div>";

        if ($commonDialog.length === 0) {
            $('body').append(html);
        } else {
            $commonDialog.remove()
            $('body').append(html);
        }
        var loginEvent = function (option) {
                if(option.action == 'login'){
                    var params = {
                        account: $("#loginForm").find("#account").val(),
                        password: $("#loginForm").find("#password").val(),
                        loginAs: "1"
                    };

                    $.ajax({
                        type: "POST",
                        async: false,
                        data: JSON.stringify(params),
                        headers: {
                            'content-type': "application/json"
                        },
                        url: GLOBAL_VAR.api()+'/user/checkLogin',
                        dataType: "json",
                        success: function (result) {
                            console.log(result);
                            if(result.code == 200){
                                let pageName   =window.location.pathname;
                                if (pageName.toLowerCase()=="/middle/armmove.html"){
                                    /*如果是非管理员账号，不给登录。*/
                                    if (result.result.userType==4){
                                        layer.msg('仅限教师可以操作，请先登录教师账户！', {icon: 5,time:500});
                                        return;
                                    }else {
                                        COOKIE_TOOL.setCookie("userInfoArm",JSON.stringify(result.result), 7);
                                    }
                                }
                                layer.msg('登录成功！', {icon: 1});

                                COOKIE_TOOL.setCookie("userInfo", JSON.stringify(result.result), 7)
                                COOKIE_TOOL.setCookie("classRoomList", JSON.stringify(result.result.classroomList), 7)
                                $commonDialog.hide();
                                console.log(COOKIE_TOOL.getCookie("classRoomList"))
                                // 教师登录
                                if (result.result.userType == 3&&pageName.toLowerCase()!="/middle/armmove.html"){

                                    // 教师保留初始年级版本
                                    COOKIE_TOOL.setCookie('gradeIdTab', result.result.grade, 1);
                                    setTimeout(function () {

                                         let pageName   =window.location.pathname;
                                        /*如果是机械页面登录不做跳转*/
                                        if (pageName!="/middle/armMOve.html"){
                                            window.location.href = window.location.origin + "/teacher/index.html";
                                        }
                                    }, 500);
                                }else{

                                    if(option.callback){
                                        setTimeout(function () {
                                            option.callback();
                                        }, 500);
                                    }else{
                                        if(option.isMid){
                                            var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('midGameInfo'));
                                            TOOL.saveMidRecord(result.result.id, gameInfo);
                                            if(gameInfo.isFinish){ //失败
                                                var $successModal = $('#successModal');
                                                $successModal.find(".name-input").hide();
                                            } else { //正确
                                                var $failureModal = $('#failureModal');
                                                $failureModal.find(".name-input").hide();
                                            }
                                        }else{
                                            var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('gameInfo'));
                                            TOOL.saveData(result.result.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);
                                            if(gameInfo.completeStatus == 0){ //失败
                                                var $failureModal = $('#failureModal');
                                                $failureModal.find(".name-input").hide();
                                            } else { //正确
                                                var $successModal = $('#successModal');
                                                $successModal.find(".name-input").hide();
                                            }
                                        }
                                    }
                                }

                                //发送在线时长统计信息
                                TOOL.sendOnlineTime()
                            }else{
                                layer.alert(result.message,{title:'温馨提示', closeBtn:false});
                            }
                        },
                        error: function (e) {
                            //alert("error: " + JSON.stringify(e))
                            //layer.msg('登录成功！', {icon: 1});
                            layer.msg(JSON.stringify(e), {icon: 5});

                        }
                    });
                }else{
                    option.callback();
                }
            };

        setTimeout(function () {
            $commonDialog = $("#common-dialog");
            $commonDialog.show();
            $commonDialog.find('.common-dialog-close').click(function () {
                $commonDialog.hide();
            });

            $commonDialog.find('.cancel-btn').click(function () {
                $commonDialog.hide();
            });

            $commonDialog.find('.confirm-btn').click(function (){
                loginEvent(option)
            });
            $commonDialog.find('.user-login-input').keydown(function(e){
                if(e.keyCode==13){
                    loginEvent(option);
                }
            });


            $commonDialog.find(".forgetPwd").click(function () {
                $(".forget-password").click();
            })

            $commonDialog.find(".register").click(function () {
                var HTML = '<div id="register">' +
                    '        <div id="register_main">' +
                    '            <div id="register_main_top">' +
                    '                <div class="top-left"><h3>用户注册</h3></div>' +
                    '            </div><!-- main头部结尾-->' +
                    '            <hr>' +
                    '            <div id="register_main_center">' +
                    '                <form id="registerForm" class="register-container">' +
                    '                    <!-- 输入框 -->' +
                    '                    <div class="registerD">' +
                    '                        <input id="phoneAndMail" type="text"' +
                    '                               placeholder="输入手机号/邮箱" />' +
                    '                    </div>' +
                    '                    <div class="registerD">' +
                    '                        <input id="verificationCode" type="text" style="width: 40%"' +
                    '                               placeholder="输入验证码" /><button id="sendVcode" class="layui-btn send-v-code" lay-submit lay-filter="formDemo">发送验证码</button><span id="secondShow"></span>' +
                    '                    </div>'+
                    '                    <div class="registerD">' +
                    '                        <input id="pwd1" type="password"' +
                    '                               placeholder="输入密码" />' +
                    '                    </div>'+
                    '                    <div class="registerD">' +
                    '                        <input id="pwd2" type="password"' +
                    '                               placeholder="输入再次输入密码" />' +
                    '                    </div>'+
                    '                </form>' +
                    '            </div><!-- main中部结尾-->' +
                    '        </div><!-- main结尾-->' +
                    '    </div>';

                var loginCallback =  function () {
                    var vcode = $("#verificationCode").val();
                    var pwd1 = $("#pwd1").val();
                    var pwd2 = $("#pwd2").val();
                    var $phoneAndMail = $("#phoneAndMail").val();

                    if(pwd1 != pwd2){
                        layer.msg("两次密码输入不一致,请重新输入", {icon: 5})
                    }

                    var url = "/user/register/account/code/" + vcode + "/type/" + regType;
                    var params = {};
                    params["phoneOrEmail"] = $phoneAndMail;
                    params["password"] = pwd1;
                    params["userType"] = "4";
                    params["accountType"] = "2";
                    params["registerFrom"] = "2";

                    AjaxUtil.get(GLOBAL_VAR.moocapi() + url, params, function (result) {
                        if (result.code == 0) {
                            if(result.code == 0){
                                setTimeout(function () {
                                    layer.msg("注册成功，请登录", {icon: 5})
                                    $(".btn-login").click();
                                }, 500)
                            }else{
                                layer.msg(result.message, {icon: 5})
                            }
                        }
                    })
                }

                TOOL.commonDialog({bgColor: 'min-bg', closeBtn: true, html: HTML, showConfirmButton: true, confirmButtonName: '注册', showCancelButton: true, size: 'min', action: 'register', callback: loginCallback}, function () {
                    addVCodeEvent(2);
                })

                var regType = "1";
                var timer;

                var addVCodeEvent = function (type) {
                    $(".send-v-code").click(function () {
                        var reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
                        var $phoneAndMail = $("#phoneAndMail").val();

                        if(!$phoneAndMail || $phoneAndMail === ""){
                            alert("请输入手机号或者邮箱");
                            return false;
                        } else{
                            if(!reg.test($phoneAndMail)){
                                if(!(/^1[3456789]\d{9}$/.test($phoneAndMail))){
                                    alert("手机号码有误，请重新填写！");
                                    return false;
                                }
                            }

                            var url = "/user/send/phone/" + $phoneAndMail + "/type/" + type;
                            var params = {};
                            if(reg.test($phoneAndMail)){
                                url = "/user/send/email/type/" + type;
                                params["email"] = $phoneAndMail;
                                regType = "2";
                            }else{
                                params["productType"] = 3;
                                regType = "1";
                            }

                            AjaxUtil.get(GLOBAL_VAR.moocapi() + url, params, function (result) {
                                if(result.code == 0){
                                    var countdown=120;
                                    $("#sendVcode").attr("disabled", true);
                                    $("#sendVcode").css("background-color", "#949494");
                                    $("#sendVcode").html('重新发送('+countdown+'s)');
                                    timer = setInterval(function () {
                                        if (countdown == 0) {
                                            clearInterval(timer);
                                            $("#sendVcode").html('重新发送');
                                            $("#sendVcode").removeAttr("disabled");
                                            $("#sendVcode").css("background-color", "#009688");
                                            countdown = 120;
                                            console.log(countdown);
                                        }else{
                                            $("#sendVcode").html('重新发送('+(countdown-1)+'s)');
                                            countdown--;
                                        }
                                    }, 1000);
                                }else{
                                    layer.msg(result.message, {icon: 5})
                                }
                            })

                            return false;
                        }

                    })
                }

            })


            $commonDialog.find(".model-bg").click(function () {
                $commonDialog.hide();
            })

            callback();
        }, 10);
    },

    getUserInfoFromCookie: function(){
        return COOKIE_TOOL.getCookie("userInfo") == "" ? null : JSON.parse(COOKIE_TOOL.getCookie("userInfo"));
    },
    checkIsLocal: function () {
        var origin = window.location.host;
        /*if(origin.indexOf("192.168.12.1") != -1 || origin.indexOf("http://120.55.81.97") != -1){
            return false;
        }else{
            return true
        }*/
        if(origin.indexOf("127.0.0.1") != -1){
            return true;
        }else{
            return false;
        }
    },
    isPC:function () {
            var userAgentInfo = navigator.userAgent;
            var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
            var flag = true;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;
                }
            }
            return flag;
    },

    /**
     * 比较两个数组的元素和元素的顺序是否一致
     * @param arr1
     * @param arr2
     */
    compareArr: function (arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        var result = true;
        for (var i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) {
                result = false;
                return false;
            }
        }
        return result;
    },

    /**
     * 比较两个数组的元素是否一致
     * @param arr1
     * @param arr2
     */
    compareArrWithOutSort: function (arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        var result = true;
        for (var i = 0; i < arr1.length; i++) {
            if (arr2.indexOf(arr1[i])<0) {
                result = false;
                return false;
            }
        }
        return result;
    },

    /**
     * 获取关卡视频信息
     * @param gameProjectId  关卡ID
     * @param pageSize  默认10
     * @param handler 结果回调处理
     */
    getLevelVideo: function (gameProjectId, handler) {
        AjaxUtil.get(GLOBAL_VAR.api() + '/projectRelevance/point/video/' + gameProjectId, null, function (result) {
            handler(result);
        });
    },

    /**
     * latex转img标签
     * @param latex
     */
    convertLatex2Img: function (content) {
        return content.replace(/\[\/f\/\$ (.*?) \$\]/g, '<img class="kfformula" src="http://cgi.c20test.com/tex2png/cgi-bin/mathtex.cgi?$1" data-latex="$1" />');
    },

    /**
     * 将img标签转latex
     * @param imgLabel
     */
    convertImg2Latex: function (content) {
        return content.replace(/<img(.*?)data-latex=\"(.*?)\"\/>/g,"[/f/$ $2 $]")
    },

    getSvgQuestion: function (question) {
        return question.replace(/\[\/f\/\$ (.*?) \$\]/g , function(){
            return MathJax.tex2svg(arguments[1]).innerHTML;
        });
    }
};

/**
 * webview页面调用
 */
window.reloadUserInfo = function () {
    if (window.MathFun) {
        //获取用户信息后将游戏记录保存
        var userInfo = JSON.parse(window.MathFun.getUserInfo());

        //从localstorage里找到当前的游戏信息
        var gameInfo = JSON.parse(COOKIE_TOOL.getCookie('gameInfo'));
        TOOL.saveData(userInfo.id, gameInfo.id, gameInfo.gradeId, gameInfo.completeStatus, gameInfo.useTime);

        $(".name-input").hide();
    }
}

window.playBackgroundMusic = function () {
    var elementById = document.getElementById('backgroundMusic');
    if (elementById) {
        elementById.load();
        var promise = elementById.play();
        if (promise !== undefined) {
            promise.then(function () {
            }).catch(function (reason) {
                console.info(reason);
                setTimeout(function () {
                    elementById.play();
                }, 500);
            });
        }
    }
};
window.stopBackgroundMusic = function () {
    var elementById = document.getElementById('backgroundMusic');
    if (elementById) {
        elementById.pause();
    }
};

window.showDebug = function(message){
    if(!$("#debugDiv").get(0)){
        $("body").append('' +
            '<!-- 调试信息 -->' +
            '<div id="debugDiv" class="debug-div">' +
            '    debug 信息:<br/>' +
            '</div>')
    }
    $("#debugDiv").append('<br/>' + message);
}
/**
 *  翻译0-9的数字为中文
 */
TOOL.parseNumToChinese = function(str1){
    str1 =  str1.replace(/0/g, "零");
    str1 =  str1.replace(/1/g, "一");
    str1 =  str1.replace(/2/g, "二");
    str1 =  str1.replace(/3/g, "三");
    str1 =  str1.replace(/4/g, "四");
    str1 =  str1.replace(/5/g, "五");
    str1 =  str1.replace(/6/g, "六");
    str1 =  str1.replace(/7/g, "七");
    str1 =  str1.replace(/8/g, "八");
    str1 =  str1.replace(/9/g, "九");
    return str1 ;
}


/**
 *  翻译0-7的数字为周
 */
TOOL.parseNumToChineseWeek = function(str1){
    str1 =  str1.replace(/0/g, "日");
    str1 =  str1.replace(/1/g, "一");
    str1 =  str1.replace(/2/g, "二");
    str1 =  str1.replace(/3/g, "三");
    str1 =  str1.replace(/4/g, "四");
    str1 =  str1.replace(/5/g, "五");
    str1 =  str1.replace(/6/g, "六");
    return str1 ;
}

/**
 *  处理 gameInfo 只保留需要存储到cookies的部分
 */
TOOL.dellGameInfo = function(gameInfo){
    return newGameInfo = {
        id: gameInfo.id,
        backImg: gameInfo.backImg,
        backMusic: gameInfo.backMusic,
        gradeId: gameInfo.gradeId,
        themeId: gameInfo.themeId,
        name: gameInfo.name,
        useTime: gameInfo.useTime,
        completeStatus: gameInfo.completeStatus
    };
}


/**
 *  处理 gameInfo 只保留需要存储到cookies的部分
 */
TOOL.dellMidGameInfo = function(gameInfo){
    return newGameInfo = {
        activityId: gameInfo.activityId,
        costTime: gameInfo.costTime,
        isFinish: gameInfo.isFinish,
        recordType: gameInfo.recordType
    };
}

//阿拉伯数字转换成大写汉字
TOOL.numberParseChina = function(money){
    //汉字的数字
    var cnNums = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    //基本单位
    var cnIntRadice = new Array('', '十', '百', '千');
    //对应整数部分扩展单位
    var cnIntUnits = new Array('', '万', '亿', '兆');
    //对应小数部分单位
    var cnDecUnits = new Array('角', '分', '毫', '厘');
    //整数金额时后面跟的字符
    var cnInteger = '';
    //整型完以后的单位
    var cnIntLast = '';
    //最大处理的数字
    var maxNum = 999999999999999.9999;
    //金额整数部分
    var integerNum;
    //金额小数部分
    var decimalNum;
    //输出的中文金额字符串
    var chineseStr = '';
    //分离金额后用的数组，预定义
    var parts;
    if (money == '') { return ''; }
    money = parseFloat(money);
    if (money >= maxNum) {
        //超出最大处理数字
        return '';
    }
    if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    //转换为字符串
    money = money.toString();
    if (money.indexOf('.') == -1) {
        integerNum = money;
        decimalNum = '';
    } else {
        parts = money.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
    }
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                //归零
                zeroCount = 0;
                if(cnNums[parseInt(n)] == '一' && cnIntRadice[m] == '十'){
                    chineseStr += cnIntRadice[m];
                }else{
                    chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                }
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
        chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
            var n = decimalNum.substr(i, 1);
            if (n != '0') {
                chineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '') {
        chineseStr += cnInteger;
    }
    return chineseStr;
}

//鼠标右键屏蔽
$(document).bind("contextmenu", function (e) {
    return false;
});

//  一下为防止JS浮点类型计算,防止精度丢失的方法
//加法
Number.prototype.add = function(arg){
    var r1,r2,m;
    try{r1=this.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2))
    return (this.mul(m) + arg.mul(m)) / m;
}

//减法
Number.prototype.sub = function (arg){
    return this.add(-arg);
}

//乘法
Number.prototype.mul = function (arg)
{
    var m=0,s1=this.toString(),s2=arg.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}

//除法
Number.prototype.div = function (arg){
    var t1=0,t2=0,r1,r2;
    try{t1=this.toString().split(".")[1].length}catch(e){}
    try{t2=arg.toString().split(".")[1].length}catch(e){}
    with(Math){
        r1=Number(this.toString().replace(".",""))
        r2=Number(arg.toString().replace(".",""))
        return (r1/r2)*pow(10,t2-t1);
    }
}

/**
 *  构建引言 显示html内容
 */
TOOL.createTipsHTML= function (tips, tipsIndex, callback){
    var tipsItem = tips[tipsIndex];
    var backStyle = "";
    if(tipsItem.backImg && tipsItem.backImg.indexOf("http") != -1){
        var backStyle = 'style="background: url(' + tipsItem.backImg + ') #b7edf9 no-repeat; background-size: 100% 100%;"'
    }
    var lucencyModalHTML = '<div id="robTipsModal" class="rob-tips-modal-root" ' + backStyle + '>' +
        '   <div class="modal-tips">' +
        '       <div class="tips-title"><h2>'+ tipsItem.title +'</h2></div>' +
        '       <div class="tips-content">'+ TOOL.getSvgQuestion(tipsItem.content) +'</div>'/* +
        '       <div class="tips-rule">'+ tipsItem.rule +'</div>'*/;

    if(tipsItem.gameProjectVideoList && tipsItem.gameProjectVideoList.length > 0){
        tipsItem.gameProjectVideoList.forEach(function (gameVideoItem, j) {
            lucencyModalHTML +='       <div class="tips-video tips-video'+ (j+1) +'" videohref="'+ gameVideoItem.videoId +'">' +
                '<img src="../../img/video-icon.png">视频案例' +(j+1)+ '</div>';
        })
    }

    if (tipsIndex>0){
        lucencyModalHTML += '       <div class="tips-pre" tipsIndex="' + tipsIndex + '">上一步</div>';
    }

    lucencyModalHTML += '       <div class="tips-ignore">跳过</div>';

    if(tips.length > 1 && tipsIndex != (tips.length-1)){
        lucencyModalHTML +='       <div class="tips-next" tipsIndex="'+tipsIndex+'">下一步</div>';
    }

    lucencyModalHTML += '   </div>' +
        '</div>';
    $('body').append(lucencyModalHTML);

    $(".tips-next").off().click(function () {
        var ctipsIndex = parseInt($(this).attr("tipsIndex"));
        if(ctipsIndex >= tips.length - 1){
            $("#videoCtr").show();
            callback();
        }else{
            $('body').find("#robTipsModal").remove();
            TOOL.createTipsHTML(tips, ctipsIndex+1, callback)
        }
    })

    $(".tips-pre").off().click(function () {
        var ctipsIndex = parseInt($(this).attr("tipsIndex"));
        if (ctipsIndex > 0) {
            $('body').find("#robTipsModal").remove();
            TOOL.createTipsHTML(tips, ctipsIndex-1, callback)
        }
    })

    $(".tips-ignore").off().click(function () {
        $("#videoCtr").show();
        callback();
    })

    if(tipsItem.gameProjectVideoList && tipsItem.gameProjectVideoList.length > 0){
        if(!$("#videoModal") || $("#videoModal").length == 0){
            var videoModalHtml = '<div id="videoModal" class="result-modal-root" style="display: none">' +
                '    <div class="close-modal" style="position: absolute;top: 5%;right: 14%;width: 3vw;"><img src="../../img/btn_close_white.png"></div>' +
                '    <div class="modal-content">' +
                '        <div class="video-js my-video">' +
                '            <video id="my-video" preload="auto" poster=""></video>' +
                '        </div>' +
                '    </div>' +
                '</div>';
            $("body").append(videoModalHtml);
        }
    }

    /* 初始化 videojs 播放器 */
    var options = {
        //poster: videoImg,//不自动播放的话，就默认显示图片
        controls: true,//不显示动作条
        autoplay: true,//是否自动播放
        width: 868,
        height: 524,
        controlBar: {
            muteToggle: false,
            fullScreen: true
        },
        playbackRates: [0.5, 1, 1.25, 1.5, 1.75, 2]//倍速
    };

    /** 开始播放视频 - 弹窗*/
    $(".tips-video").click(function() {
        var videoUrl = $(this).attr("videohref");
        videojs("my-video", options, function() {
            window.myPlayer = this;
            $("#videoModal .video-con #my-video source").attr("src", videoUrl);
            myPlayer.src(videoUrl);
            myPlayer.load(videoUrl);
            myPlayer.play();
        });
        $('#videoModal').show()

        var soundStatus = TOOL.getSoundStatus();
        if(soundStatus){
            window.stopBackgroundMusic();
        }
    });

    // 模态窗消失时，关闭视频
    $('#videoModal').find(".close-modal").on('click', function() {
        $('#videoModal').hide()
        myPlayer.pause();

        var soundStatus = TOOL.getSoundStatus();
        if(soundStatus) {
            window.playBackgroundMusic();
        }
    });
}

/**
 * 初始化 引言内容 - 无则不执行
 * @param tipsIndex
 * @param callback
 */
TOOL.initIntroduction = function (callback) {
    try {
        var gameProjectId = (TOOL.getQueryVariable("gameProjectId"))
        var tips = [];
        var params = {projectId : gameProjectId};
        AjaxUtil.postWithJson(GLOBAL_VAR.api()+'/introduction/config/list', params, function (result) {
            if(result && result.length > 0){
                result.forEach(function (introConfig) {
                    introConfig.introduction.gameProjectVideoList = introConfig.gameProjectVideoList;
                    tips.push(introConfig.introduction)
                })
                console.log(tips)
            }
        })
        //没有的引言内容话就直接加载
        if(tips.length == 0){
            if(callback){ callback(); }
        }else{
            $("#videoCtr").hide()
            TOOL.createTipsHTML(tips,0, function(){
                $("#robTipsModal").hide();
                if(callback){ callback(); }
            })
        }
    }catch (e) {
        console.log(e);
        if(callback){ callback(); }
    }
}

/**
 * 初始化 引言内容 - 无则不执行
 * @param tipsIndex
 * @param callback
 */
TOOL.initMidIntroduction = function (callback) {
    try {
        var gameProjectId = (TOOL.getQueryVariable("activityId"))
        var tips = [];
        var params = {projectId : gameProjectId, versionMiddle: 1};
        AjaxUtil.postWithJson(GLOBAL_VAR.api()+'/introduction/config/list', params, function (result) {
            if(result && result.length > 0){
                result.forEach(function (introConfig) {
                    introConfig.introduction.gameProjectVideoList = introConfig.gameProjectVideoList;
                    tips.push(introConfig.introduction)
                })
                console.log(tips)
            }
        })
        //没有的引言内容话就直接加载
        if(tips.length == 0){
            if(callback){ callback(); }
        }else{
            $("#videoCtr").hide()
            TOOL.createTipsHTML(tips,0, function(){
                $("#robTipsModal").hide();
                if(callback){ callback(); }
            })
        }
    }catch (e) {
        console.log(e);
        if(callback){ callback(); }
    }
}

TOOL.startDurationStatistic = function(sourcePage, player, userId, videoUrl, videoName, pointId, projectId, themeId, gradeId, themeName, pointName){
    var duration = 0;
    var totalDuration = 0;
    var seeTimes = 0;

    GLOBAL_VAR.myTimer = setInterval(function () {
        duration ++;
        seeTimes ++;
        if(duration%10 == 0){
            sendDuration(duration);
            duration = 0;
        }
    }, 1000)

    /*
     * 可用的事件列表 durationchange, ended //播放结束, firstplay, fullscreenchange, loadedalldata,
     * loadeddata, loadedmetadata, loadstart, pause , play , progress, seeked, seeking,
     * timeupdate, volumechange, waiting,resize inherited
     */
    player.on('ended', function() {
        // console.log("video end........")
        sendDuration((duration));
        window.clearInterval(GLOBAL_VAR.myTimer);
        duration = 0;
    });

    player.on('loadedmetadata',function(){
        totalDuration = player.duration();
        console.log(totalDuration)
    });

    player.on('pause', function() {
        var $player = this;
        if(!$("#videoModal").is(':visible')){
            AjaxUtil.getUserInfo(function (userInfo) {
                if (userInfo) {
                    AjaxUtil.getGameInfo(function (data) {
                        if (data) {
                            var logParams = {};
                            logParams["userId"] = userInfo.id;
                            logParams["logType"] = "10";
                            logParams["logChildType"] = "1011";
                            var msg = "视频学习-"+ TOOL.numberParseChina(gradeId)+ "年级，主题【" + themeName + "】" + data.projectNumber +"，知识点视频【"  + videoName + "】，学习时长："+ TOOL.timeDiffHourMinSec($player.currentTime()) +"。";
                            logParams["description"] = msg;
                            AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/log/manager/openapi/save', logParams, function (res) {
                                if(res.code === 200){
                                }else{
                                    console.log(msg + "日志记录失败")
                                }
                            })
                        }
                    })

                }
            })
        }
    });

    var dataparam = {};
    dataparam['userId'] = userId;
    dataparam['sourcePage'] = sourcePage;
    dataparam['videoUrl'] = videoUrl;
    dataparam['videoName'] = videoName;
    dataparam['pointId'] = pointId;
    dataparam['projectId'] = projectId;
    dataparam['themeId'] = themeId;
    dataparam['gradeId'] = gradeId;

    function sendDuration(durationOne){
        dataparam['watchTotalTime'] = parseInt(durationOne);
        dataparam['videoLength'] = totalDuration;
        AjaxUtil.postWithJson(GLOBAL_VAR.api() + '/projectRelevance/watch/video', dataparam, function (data) {

        });
    }
}


TOOL.formatDate = function (date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    var o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }

    for (var k in o) {
        var m = '(' + k +')';
        if (new RegExp(m).test(fmt)) {
            var str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
        }
    }
    return fmt
}

TOOL.timeDiffHourMinSec = function(s) {
    if ((typeof s == "string") && s.indexOf(",") != -1) {
        s = s.replace(",", "");
        s = parseInt(s);
    }
    if(s <= 1){
        return s +"秒";
    }
    var hour = parseInt(s  / 60 / 60, 10);//计算剩余的小时数
    var min = parseInt(s  / 60 % 60, 10);//计算剩余的分钟数
    var sec = parseInt(s % 60, 10);//计算剩余的秒数
    var str = ""
    if (hour != 0) {
        str += hour + "时";
    }
    if (min != 0) {
        str += min + "分";
    }
    if (sec != 0) {
        str += sec + "秒";
    }
    return str;
}

TOOL.timeDiffHourMinSec2 = function(s, hd, md, sd) {
    if ((typeof s == "string") && s.indexOf(",") != -1) {
        s = s.replace(",", "");
        s = parseInt(s);
    }
    if(s <= 1){
        return s + sd;
    }
    var hour = parseInt(s  / 60 / 60, 10);//计算剩余的小时数
    var min = parseInt(s  / 60 % 60, 10);//计算剩余的分钟数
    var sec = parseInt(s % 60, 10);//计算剩余的秒数
    var str = ""
    if (hour != 0) {
        str += hour + hd;
    }
    if (min != 0) {
        str += min + md;
    }
    if (sec != 0) {
        str += sec + sd;
    }
    return str;
}

function padLeftZero(str) {
    return ('00' + str).substr(str.length)
}

TOOL.sendOnlineTime = function () {
    AjaxUtil.getUserInfo(function (userInfo) {
        if (userInfo) {
            var params = {
                "userId": userInfo.id,
                "type":1,
                "sourcePage":"/mathfun/fromWeb",
                "desc": "在线",
                "duration": times
            }


            AjaxUtil.putJson(GLOBAL_VAR.api() + "/userLog", params, function (data) {
                // console.log(data)
                times = 0;
                COOKIE_TOOL.setCookie("onlineTime", times)
            })
        }
    })
}

TOOL.formatRankName = function(name) {
    var newStr;
    if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
    } else if (name.length == 3) {
        newStr = name.substr(0, 1) + "**";
    } else if (name.length > 3) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
            char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
    } else {
        newStr = name;
    }
    return newStr;
}


function JumpToRecordAnswer(data) {
     let id  =$(data).attr("jumpid");
     let schoolRank  =$(data).parent().parent().find(".schoolrank").text();
     let allRank  =$(data).parent().parent().find(".allRank").text();
     let osType =$(data).parent().parent().find(".os-type").attr("src").indexOf("1")>-1? 1:0;
    let hasAnswer =$(data).attr("hasAnswer");

    if (JSON.parse(hasAnswer)){
         window.open("/middle/showSquare.html?code=" + id + "&schoolRank="+schoolRank+"&allRank="+allRank + "&language=record" +"&language=record"+"&osType="+osType , 'scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes')
     }else {
         layer.msg("此做题答案未记录!")
     }
}

TOOL.openGamePage = function (url, actId, sectionId, method, unlock, sectionName) {
    var url = window.location.origin + url + "?activityId=" + actId + "&from=magic&sectionId="+sectionId + "&method="+method + "&sectionName="+sectionName;
    if(unlock == "false"){
        layer.msg("请先完成之前章节的答题，解锁本章节后才可以答题！", {icon: 7})
    }else{
        if(window.MagicPuzzle){
            window.MagicPuzzle.jumpWebActivity(url);
        }else{
            window.open(url)
        }
    }
}